package ilincar.systemcore.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Locale;

/**
 * Created by ilincar on 2016/12/9.
 */

public class IlincarUtils {

    public static final String BIRTH_DATE_FORMAT = "yyyy-MM-dd";
    public static final String ONLY_DATE_FORMAT = "MM-dd";

    private static char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static String MAC = null;
    /**
     * 通过shell 获取mac地址
     * @return
     */
    public static String getIntMacByShell() {
        if (MAC != null && !"".equals(MAC))
            return MAC;
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            while ((line = input.readLine()) != null) {
                macSerial += line.trim();
            }
            input.close();

            if(!macSerial.equals("")){
                String parstr = macSerial.replace(":", "");
                long value = Long.valueOf(parstr, 16);
                return MAC = String.valueOf(value);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return MAC;
    }


    /**
     * 获取10进制的MAC地址
     *
     * @param context
     * @return
     */
    public static String getIntMacAddress(Context context) {
        String address = getMacAddress(context);
        if (address == null || address.equals("")) {
            return "";
        }
        String parstr = address.replace(":", "");
        long value = Long.valueOf(parstr, 16);
        return String.valueOf(value);
    }


    /**
     * 获取设备WIFI的MAC地址
     *
     * @param context
     * @return
     */
    public static String getMacAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String mac = "";
        if (wifiInfo != null) {
            mac = wifiInfo.getMacAddress();
        }
        if (mac == null) {
            mac = "";
        }
        return mac;
    }

    /**
     * 获取手机唯一标识符，
     * 先获取IMEI号
     *
     * @param context
     * @return
     */
    public static String getImei(Context context) {
        TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String imei = manager.getDeviceId();
        return imei;
    }

    /**
     * 获取SIM卡iccid
     * @return
     */
    public static String getICCID(Context context){
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getSimSerialNumber();
    }

    /**
     * 判断是否有网
     *
     * @param context
     * @return
     */
    public static boolean hasNetwork(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        return (info != null && info.isAvailable() && info.isConnected());
    }


    /**
     * 判断是否有wifi
     *
     * @param context
     * @return
     */
    public static boolean hasWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        return info != null && info.isAvailable() && info.isConnected()
                && info.getType() == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * 解析 respone 数据，转换成UTF-8
     * @param response
     * @return
     * @throws IOException
     */
    public static String getEncodeAndGzip(String response) throws IOException{
        return URLDecoder.decode(response, "UTF-8");
    }

    /**
     * 加密操作
     * @param respone
     * @return
     * @throws IOException
     */
    public static String setEncodeAndGzip(String respone) throws IOException{
        return URLEncoder.encode(respone, "UTF-8");
    }

    /**
     * 解析地址,返回 IP地址
     * @param url
     * @return
     */
    public static String getInetAddress(String url){
        String address = "";
        try {
            InetAddress inetAddress = InetAddress.getByName(url);
            address = inetAddress.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return address;
    }

    public static byte[] md5Byte(String encryptStr) throws Exception{
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(encryptStr.getBytes("UTF-8"));
        return messageDigest.digest();
    }

    public static String md5(String encryptStr) throws Exception{
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(encryptStr.getBytes("UTF-8"));
        byte[] digest = messageDigest.digest();
        StringBuffer md5 = new StringBuffer();
        for (int i = 0; i < digest.length; i++){
            md5.append(Character.forDigit((digest[i] & 0xF0) >> 4, 16));
            md5.append(Character.forDigit((digest[i] & 0xF), 16));
        }
        encryptStr = md5.toString();
        return encryptStr;
    }

    /**
     * 根据输入的时间获取 其到现在的时间长度
     *
     * @param lastDate
     * @return
     */
    public static String getTimePassed(Date lastDate) {
        Calendar now = Calendar.getInstance();
        Calendar bef = Calendar.getInstance();
        bef.setTime(lastDate);
        long dayDiff = getDateDiff(now, bef);
        if (dayDiff < 0)
            return "刚刚";
        if (dayDiff > 1) {
            if (now.get(Calendar.YEAR) == bef.get(Calendar.YEAR)) {
                return new SimpleDateFormat(ONLY_DATE_FORMAT, Locale.getDefault()).format(lastDate);
            } else {
                return new SimpleDateFormat(BIRTH_DATE_FORMAT, Locale.getDefault()).format(lastDate);
            }
        }
        if (dayDiff == 1)
            return "昨天";
        long msDiff = now.getTimeInMillis() - bef.getTimeInMillis();
        long minDiff = msDiff / (1000 * 60);

        if (minDiff == 1 || minDiff == 0)
            return "刚刚";
        if (minDiff < 60)
            return minDiff + "分钟前";
        long hourDiff = minDiff / 60;
        return hourDiff + "小时前";
    }

    private static long getDateDiff(Calendar now, Calendar bef) {
        int msInDay = 1000 * 60 * 60 * 24;
        Calendar nowTrunc = truncateDate(now);
        Calendar befTrunc = truncateDate(bef);
        long msDiff = nowTrunc.getTimeInMillis() - befTrunc.getTimeInMillis();
        long dayDiff = msDiff / msInDay;
        return dayDiff;
    }

    public static Calendar truncateDate(Calendar calender) {
        return truncateDate(calender.getTime());
    }

    public static Calendar truncateDate(Date d) {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c;
    }


    public static String videoEncode(String rawpass, Object object){
        String saltePass = mergePasswordAndSalt(rawpass, object);
        try{
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] digest = messageDigest.digest(saltePass.getBytes("UTF-8"));
            return byteToHex(digest);
        }catch (Exception e){
            e.printStackTrace();
        }
        return rawpass;
    }

    private static String mergePasswordAndSalt(String passwd, Object object){
        if(object == null || "".equals(object.toString().trim())){
            return passwd;
        }
        return passwd + object.toString();
    }

    private static String byteToHex(byte[] bytes){
        int len = bytes.length;
        char[] result = new char[2 * len];
        int j = 0;
        for(int i = 0; i < len; i++){
            result[j++] = HEX_CHARS[(0xF0 & bytes[i]) >>> 4];
            result[j++] = HEX_CHARS[(0x0F & bytes[i])];
        }
        return new String(result);
    }
}
